#!/usr/bin/env node

const fs = require('fs');
const os = require('os');
const path = require('path');

const verbose = process.argv.includes('-v');

const source = path.join(__dirname, 'build/src/cli.js');
const targetDir = path.join(__dirname, 'bin');
const target = path.join(targetDir, 'wallet');

if (!fs.existsSync(targetDir)) {
  fs.mkdirSync(targetDir);
}

try {
  const lstat = fs.lstatSync(target);
  if (lstat.isSymbolicLink() || lstat.isFile()) {
    verbose && console.info('Removing stale file:', target);
    fs.rmSync(target);
  }
} catch (e) {
  verbose && console.info('No stale file to remove:', e.message);
  // Ignore errors if the file does not exist
}

try {
  fs.chmodSync(source, '755');
} catch (e) {
  if (os.platform() !== 'win32') {
    throw e;
  }
  // Ignore errors on Windows
}

verbose && console.info('Creating symlink: ', source, ' -> ', target);
fs.symlinkSync(source, target, 'file');
